package com.tom.zojbackendserviceclient.service;

import com.tom.zojbackendcommon.common.ErrorCode;
import com.tom.zojbackendcommon.constant.UserConstant;
import com.tom.zojbackendcommon.exception.BusinessException;
import com.tom.zojbackendmodel.model.entity.User;
import com.tom.zojbackendmodel.model.enums.UserRoleEnum;
import com.tom.zojbackendmodel.model.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * 用户服务
 *
 */

//开启openFeign的支持
//@FeignClient(name = "zoj-backend-user-service", path = "/api/user/inner",fallback = UserFeignClientFallback.class)
@FeignClient(name = "zoj-backend-user-service", path = "/api/user/inner")

public interface UserFeignClient{

    /**
     * 获取用户id
     * @param userId
     * @return
     */
    @GetMapping("/get/id")
    User getById(@RequestParam("userId") long userId);

    /**
     * 获取用户全部id
     * @param userIds
     * @return
     */
  //todo:collection
    @GetMapping("/list/Ids")
    List<User> listByIds(@RequestParam("userIds") Set<Long> userIds);


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request){
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }
  //减少网络传输的不稳定性，直接在这里面实现，就不经过调用服务实现了

    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */

    default boolean isAdmin(User user){
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
//简单代码并且没有涉及到数据库的操作代码，可以直接在默认方法中实现，不需要再调用服务了

    /**
     * 获取脱敏的已登录用户信息
     *
     * @return
     */
    default UserVO getUserVO(User user){
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }





}
